package com.qc31.monitorlib.ui.stopcar

import android.view.WindowManager
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.qc31.baselib.custom.timer.CustomDatePicker
import com.qc31.baselib.custom.timer.DateFormatUtils
import com.qc31.baselib.rx.queryThrottle
import com.qc31.baselib.rx.textChangesNoLong
import com.qc31.baselib.utils.ActivityResultUtil.launchAct
import com.qc31.baselib.utils.ActivityResultUtil.registerResultOk
import com.qc31.baselib.utils.ToolbarHelper
import com.qc31.baselib.utils.isFastClick
import com.qc31.baselib.utils.startActivityTo
import com.qc31.comlib.Keys
import com.qc31.comlib.TimeUtil
import com.qc31.comlib.adapter.ChooseTimeAdapter
import com.qc31.comlib.choose.car.ChooseCarActivity
import com.qc31.comlib.databinding.IncludeChooseCarTimeBinding
import com.qc31.comlib.databinding.IncludeChooseFastTimeBinding
import com.qc31.comlib.databinding.IncludeRecyclerWrapBinding
import com.qc31.monitorlib.R
import com.qc31.monitorlib.base.BaseReportViewModel
import com.qc31.monitorlib.base.BaseSureActivity
import com.qc31.monitorlib.databinding.ActivityStopCarBinding
import com.qc31.monitorlib.uitls.DataUtil

/** @Author Jasper @Time 2020/12/11 @Desc 停车统计 */
class StopCarActivity : BaseSureActivity<ActivityStopCarBinding>(ActivityStopCarBinding::inflate) {

    private lateinit var mReportVB: IncludeChooseFastTimeBinding
    private lateinit var mRecyclerVB: IncludeRecyclerWrapBinding
    lateinit var mChooseVB: IncludeChooseCarTimeBinding

    private val mViewModel by viewModels<StopCarViewModel>()


    val mBaseViewModel: BaseReportViewModel
        get() = mViewModel

    val titleId: Int
        get() = R.string.title_report_stop_car

    override fun initView() {
        super.initView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        mReportVB = IncludeChooseFastTimeBinding.bind(binding.root)
        mRecyclerVB = IncludeRecyclerWrapBinding.bind(binding.root)
        mChooseVB = IncludeChooseCarTimeBinding.bind(binding.root)
        if (titleId != 0) {
            ToolbarHelper.setToolbar(this, titleId)
        }
        mBaseViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)


        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 4)
        mRecyclerVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mBaseViewModel.timeList)
            setOnItemClickListener { _, _, position ->
                index = position
                notifyDataSetChanged()
                mBaseViewModel.chooseTime(position)
            }
        }

        mBaseViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvStartTime.setRightText(it)
        }

        mBaseViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvEndTime.setRightText(it)
        }

        initIntent()
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)
        mViewModel.dataObserver().autoDispose(scopeProvider).subscribe {
            DataUtil.stopCar = it
            startActivityTo<StopCarInfoActivity>(this) {
                putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                putExtra(
                    Keys.INTENT_TIME,
                    "${
                        mChooseVB.lrvStartTime.getRightText().substring(0, 10)
                    }  ~  ${mChooseVB.lrvEndTime.getRightText().substring(0, 10)}"
                )
            }
        }
    }


    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        val carName = intent.getStringExtra(Keys.INTENT_PLATE) ?: ""
        if (carId == null) return
        mBaseViewModel.carId = carId
        mBaseViewModel.carName = carName
        mChooseVB.lrvChooseCar.setRightText(carName)
        mChooseVB.lrvChooseCar.isEnabled = false
    }

    override fun setListener() {
        mChooseVB.lrvChooseCar.rightClick().autoDispose(scopeProvider).subscribe {
            launcher.launchAct<ChooseCarActivity>(this)
        }

        mChooseVB.lrvStartTime.rightClick().autoDispose(scopeProvider).subscribe {
            mBaseViewModel.isStart = true
            mDatePicker.show(mChooseVB.lrvStartTime.getRightText())
        }
        mChooseVB.lrvEndTime.rightClick().autoDispose(scopeProvider).subscribe {
            mBaseViewModel.isStart = false
            mDatePicker.show(mChooseVB.lrvEndTime.getRightText())
        }

        mSureVB.tvSure.queryThrottle().autoDispose(scopeProvider).subscribe {
            if (isFastClick()) return@subscribe
            val startTime = mChooseVB.lrvStartTime.getRightText()
            val endTime = mChooseVB.lrvEndTime.getRightText()
            mBaseViewModel.isParamOk(startTime, endTime)
        }
        binding.editStopLong.textChangesNoLong().autoDispose(scopeProvider).subscribe {
            if (!it.isNullOrEmpty()) {
                if (it.toInt() > 600) {
                    binding.editStopLong.setText("600")
                    binding.editStopLong.setSelection(binding.editStopLong.text.length)
                }
            }
            mViewModel.duration = it.toString()
        }
        binding.flSwitchACC.setOnClickListener {
            mViewModel.switchAcc = !mViewModel.switchAcc
            binding.ivSwitchAcc.isSelected = mViewModel.switchAcc
        }
    }

    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.normalDate,
            mBaseViewModel.nowTimeFormat(),
            !mBaseViewModel.isSimple
        ).apply {
            setCanShowPreciseTime(!mBaseViewModel.isSimple)
        }
    }


    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, !mBaseViewModel.isSimple)

            if (mBaseViewModel.isStart) {
                mChooseVB.lrvStartTime.setRightText(time)
            } else {
                mChooseVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
//                val videos = it.getStringExtra(Keys.VIDEO)
            mChooseVB.lrvChooseCar.setRightText(carName)
            mBaseViewModel.carName = carName
            mBaseViewModel.carId = carId
        }

    }
}